﻿namespace Oddo.Concept.Crm.Server.Repository.Services
{
    using System;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Practices.Unity;
    using Oddo.Concept.Crm.Common.Communication.Interfaces;
    using Oddo.Concept.Crm.Common.Services;
    using Oddo.Concept.Crm.Models;
    using Oddo.Concept.Crm.Repository.Common.Contracts;
    using Oddo.Concept.Crm.Server.Repository.Business;

    public class RepositoryServicesProvider : ServiceProviderBase, IRepositoryServices
    {
        [Dependency]
        public ICountryBusiness CountryBusiness { get; set; }

        public IFindResponse<Country> FindCountries(CountryFindRequest request)
        {
            var response = new CountryFindResponse();

            if (request!=null && !string.IsNullOrWhiteSpace(request.Code) && !string.IsNullOrWhiteSpace(request.Name))
                response.Values = CountryBusiness.Query(c => c.Code.StartsWith(request.Code, StringComparison.InvariantCultureIgnoreCase) && c.Name.StartsWith(request.Name, StringComparison.InvariantCultureIgnoreCase)).ToList();
            else if (request != null && string.IsNullOrWhiteSpace(request.Code) && !string.IsNullOrWhiteSpace(request.Name))
                response.Values = CountryBusiness.Query(c => c.Name.StartsWith(request.Name, StringComparison.InvariantCultureIgnoreCase)).ToList();
            else if (request != null && !string.IsNullOrWhiteSpace(request.Code) && string.IsNullOrWhiteSpace(request.Name))
                response.Values = CountryBusiness.Query(c => c.Code.StartsWith(request.Code,StringComparison.InvariantCultureIgnoreCase) ).ToList();
            else
                response.Values = CountryBusiness.Query().ToList();

            return response;
        }

        public Task<IFindResponse<Country>> FindCountriesAsync(CountryFindRequest request, CancellationToken cancellationToken)
        {
            var source = new TaskCompletionSource<IFindResponse<Country>>();
            source.SetResult( FindCountries(request) );
            return source.Task;
        }
    }
}